<?php
/**
 * ClassName: BedService
 * Description: 床位管理Service
 * @Author 周昌
 * @Create 2023/11/8 14:00
 */

namespace service\admin;


use libs\Tool;
use service\BaseService;
use think\Db;

class BedService extends BaseService
{
    protected static $model='model\BedModel';
    public static $is_empty=[0=>'否',1=>'是'];//是否空床
    public static $is_empty_index=['no'=>0,'yes'=>1];//是否空床
    public function __construct()
    {
        parent::__construct();
    }
    //空床状态 select 选择
    public static function bedIsEmptySelect()
    {
        static $bed_is_empty=[];
        if(empty($bed_is_empty)){
            foreach (self::$is_empty as $k=>$v){
                $row=[];
                $row['id']=$k;
                $row['name']=$v;
                $bed_is_empty[]=$row;
            }
            array_unshift($bed_is_empty,['id'=>'','name'=>'-----请选择-----']);
        }
        return $bed_is_empty;
    }

    /**
     * #User: Administrator
     * #Time: 2023/12/29 14:38
     * #Author:周昌
     * #Description: 更新床位状态
     * @param int $bed_id 床位主键id
     * @param int $is_empty 是否空床 0：否 1：是
     * @return array
     */
    public static function setEmpty($bed_id)
    {
        $is_empty=self::$model::getValue(['id'=>$bed_id],'is_empty');
        if($is_empty==self::$is_empty_index['no']){
            Db::startTrans();
            try {
                $res=self::edit($bed_id,['is_empty'=>self::$is_empty_index['yes']]);
                if($res['code']==0){
                    Db::rollback();
                    return Tool::Error('床位状态更新失败');
                }
                //自动分床
                $result=WaitService::autoBed();
                if($result['code']==0){
                    Db::rollback();
                    return Tool::Error('分配床位失败');
                }
                Db::commit();
                return Tool::Success();
            }catch (\Exception $exception){
                Db::rollback();
                return Tool::Error($exception->getMessage());
            }

        }else{
            return Tool::Success();
        }

    }
    //列表数据
    public static function getAjaxData($where)
    {
        $table = self::$model::order('id desc');
        return self::tableJsonData($table, $where, function ($data){
            $data['room_name'] = $data['room_id']?RoomService::getNameByKey($data['room_id'],''):'';
            $data['hospital_name'] = $data['hospital_id']?HospitalService::getNameByKey($data['hospital_id'],'','id,name','id','hospital_key_name'):'';
            return $data;
        });
    }

}